(function () {
    let startBtn = document.querySelector(".controller-right");
    let lists = document.querySelectorAll(".prize-list");
    let numberTxt = document.querySelector(".number-txt");
    let maskDialog = document.querySelector(".mask-dialog");
    let closeBtn = document.querySelector(".close");
    let againBtn = document.querySelector(".confirm-btn");
    let dialogContent = document.querySelector(".content");

    let timer = null;

    let index = -1;
    let currentIndex = null;
    let number = 5;

    let init = function () {
        numberTxt.innerHTML = number;
        initEvent();
    }

    let initEvent = function () {
        startBtn.addEventListener('click', handleStartClick);
        closeBtn.addEventListener('click', handleCloseDialog);
        againBtn.addEventListener('click', handleAgainClick);
    }

    let handleStartClick = function () {
        render();
    }

    let handleOpenDialog = function () {
        if (currentIndex !== 4) {
            let content = lists[currentIndex].innerHTML;
            dialogContent.innerHTML = content;
        } else {
            dialogContent.innerHTML = '谢谢参与';
        }
        if (number <= 0) {
            againBtn.innerHTML = '确定'
        }

        maskDialog.style.display = 'block';
    }

    let handleCloseDialog = function () {
        maskDialog.style.display = 'none';
    }

    let handleAgainClick = function () {
        maskDialog.style.display = 'none';
        render();
    }

    let render = function () {
        if (number <= 0 || timer) {
            return;
        }
        --number;
        numberTxt.innerHTML = number;
        let num = 3400 + Math.floor(Math.random() * 1600)
        timer = setInterval(function () {
            num -= 200;
            currentIndex = ++index % lists.length;

            if (num <= 0) {
                clearInterval(timer)
                timer = null;
                handleOpenDialog();
            }
            lists.forEach(function (node) {
                node.classList.remove('active');
            })
            lists[currentIndex].classList.add('active');
        }, 50)
    }

    init();
})()